<template>
  <div class="app-container">
    <a-title />
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="报告名称" prop="costName">
        <el-input
          v-model="queryParams.costName"
          placeholder="请输入造价名称"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="报告号" prop="costNo">
        <el-input
          v-model="queryParams.costNo"
          placeholder="请输入造价号"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="报告类型" prop="costType">
        <el-input
          v-model="queryParams.costType"
          placeholder="请输入报告类型"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="业务名称" prop="businessId">
        <el-select v-model="queryParams.businessId" clearable placeholder="业务名称" :filterable="true" style="width: 240px">
          <el-option
            v-for="item in businessOptionsQuery"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="业务类别" prop="businessType">
        <el-cascader
          clearable
          v-model="queryParams.businessType"
          :options="categoryOptions"
          :show-all-levels="false"
          :props="{ value: 'id',emitPath:false }"
          filterable
          style="width: 240px"
          placeholder="请选择业务类别"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入申请人"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盖章日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8"  v-if="closureStatus">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增造价报告号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
        <!--v-hasPermi="['system:no:export']"-->
      </el-col>
    </el-row>

    <el-table
      stripe
      v-loading="loading"
      :data="bmsCostNoList"
      :default-sort="{prop: 'createTime', order: 'ascending'}"
      @sort-change="tableSortChange"
    >
      <el-table-column
        label="报告名称"
        align="left"
        prop="costName"
        width="260"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column
        label="报告号"
        align="center"
        prop="costNo"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        width="150"
      />
      <el-table-column
        label="报告类型"
        align="center"
        prop="costType"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column
        label="报告号状态"
        align="center"
        prop="businessStatus"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.businessType" :type="scope.row.statusType" disable-transitions>{{
            scope.row.statusText
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="业务名称"
        align="left"
        prop="businessName"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        width="260"
      />
      <el-table-column
        label="业务类别"
        align="center"
        prop="businessType"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column
        label="申请人"
        align="center"
        prop="createBy"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column
        label="盖章日期"
        align="center"
        prop="stampTime"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      >
      <template slot-scope="scope">
            <span>{{ parseTime(scope.row.stampTime,'{y}-{m}-{d} ') }}</span>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <a v-if="!scope.row.businessType" @click="handleView(scope.$index, scope.row)">
              <i class="el-icon-copy-document aicon" />历史数据迁移
            </a>
          </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报告号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" @close="cancel">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="业务名称" prop="businessId">
          <el-select
            v-model="business.businessData"
            filterable
            placeholder="请选择业务名称"
            style="width:95%;"
            @change="getShowReportTypeBidding"
          >
            <el-option
              v-for="item in businessOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportTypeName">
          <el-select v-model="business.reportTypeName" placeholder style="width:95%;">
            <el-option v-for="item in reportTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button type="primary" @click="submitForm">新增报告号</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 历史数据迁移对话框 -->
    <el-dialog title="历史数据迁移" :visible.sync="visible" width="60%" @close="visible = false">
      <el-form ref="queryForm" :model="business" label-width="80px">
        <el-form-item label="业务名称" prop="businessId">
          <el-select
            v-model="business.businessData"
            filterable
            placeholder="请选择业务名称"
            style="width:95%;"
            @change="getShowReportTypeBidding"
          >
            <el-option
              v-for="item in businessOptions"
              :key="item.index"
              :label="item.name"
              :value="item.guid"
            />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportTypeName">
          <el-select v-model="business.reportTypeName" placeholder style="width:95%;">
            <el-option v-for="item in reportTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button type="primary" @click="submitMigrateForm">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  listBmsCostNo,
  getBmsCostNo,
  delBmsCostNo,
  addBmsCostNo,
  updateBmsCostNo,
  exportBmsCostNo,
  checkBmsCostNo,
  updateBmsCostNoHistory
} from "@/api/projectWorkbench/projectList/costNo";
import { listBusinessManagement,checkProject } from "@/api/projectWorkbench/projectList/businessManagement";
import { listNoCostNoList } from "@/api/projectWorkbench/projectList/businessManagement";
import { treeselect } from "@/api/system/business_category";
import { getBpmParams } from "@/api/workflow/workflow";
import { checkProjectStatus } from "@/api/projectWorkbench/projectGlance";
import aTitle from "@/components/Title";

export default {
  name: "BmsCostNo",
  components: { aTitle },
  data() {
    return {
      // 遮罩层
      loading: true,
      categoryOptions:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      dateRange: [],
      businessOptionsQuery:[],
      businessOptions: [],
      // 总条数
      total: 0,
      // 造价报告号表格数据
      bmsCostNoList: [],
      reportTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        costNo: undefined,
        costName: undefined,
        costType: undefined,
        createBy: undefined,
        createTime: undefined,
      },
      // 表单参数
      form: {},
      //项目结项状态
      closureStatus: false,
      // 表单校验
      rules: {},
      business: {
        businessData: "",
        reportTypeName: ""
      },
      visible: false,
    };
  },
  created() {
    checkProjectStatus(this.$route.params.id).then(res=>{
      if(res.data){
        this.closureStatus = true;
      }
      
    });

    this.getList();

    treeselect().then(res => {
      if (res.code === 200) {
        this.categoryOptions = res.data;
      }
    });
  
    listBusinessManagement({ projectId: this.$route.params.id }).then(res => {
      if (res.code === 200) {
        this.businessOptionsQuery = res.rows;
      }
    });
  },
  mounted(){
    document.title=document.getElementById("projectNameTitle").innerHTML;
  },
  methods: {
    /** 查询造价报告号列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.$route.params.id;
      listBmsCostNo(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          //this.bmsCostNoList = response.rows;

           this.bmsCostNoList = response.rows.map((item) => {
            if (item.businessStatus === "1") {
              item.statusText = "作废";
              item.statusType = "danger";
            }else{
              if(item.costNo){
                item.statusText = "有效";
                item.statusType = "success";
              }else{
                if(item.businessType){
                  item.statusText = "申请中";
                  item.statusType = "info";
                }
              }
            }

            if (item.archiveStatus === "0") {
              item.archiveStatusText = "未归档";
            } else if (item.archiveStatus === "1") {
              item.archiveStatusText = "已归档";
            } else if (item.archiveStatus === "2") {
              item.archiveStatusText = "归档中";
            }
            return item;
          });
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.refreshData();
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guid: undefined,
        businessId: undefined,
        costNo: undefined,
        costName: undefined,
        costType: undefined,
        createBy: undefined,
        createTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.guid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getBusinessOptions();
      this.title = "添加造价报告号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const guid = row.guid || this.ids;
      getBmsCostNo(guid).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改造价报告号";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.getList();
      if (!this.business.businessData) {
        this.msgError("业务不能为空！");
        return false;
      }
      if (!this.business.reportTypeName) {
        this.msgError("报告类别不能为空！");
        return false;
      }
      //判断是否能发起流程
      checkProject(this.$route.params.id,this.business.businessData.split(";")[0]).then(res=>{
        if(res.data===1){
          this.submitFormSec();
        }else{
          this.msgError("本业务已不在服务范围内，不能新增造价报告号！");
        }
      });
    },submitFormSec(){
      

      var checkParams = {
        businessId: this.business.businessData.split(";")[0],
        reportType: this.business.reportTypeName
      };
      var params = {
        businessTypeId: this.business.businessData.split(";")[1],
        projectId: this.$route.params.id,
        businessId: this.business.businessData.split(";")[0]
      };
      checkBmsCostNo(checkParams).then(res => {
        if (res.code === 200 && res.data === 0) {
          this.getBpmParamsMethod(params);
        } else {
          this.msgInfo(
            "本业务已生成造价报告号，请勿重复申请！点击刷新按钮重新载入数据！"
          );
        }
      });
    },getBpmParamsMethod(params) {
      getBpmParams(params).then(res => {
        if (res.code === 200) {
          this.gotoBpm(
            res.data,
            "costReportNo",
            this.business.reportTypeName
          );
        }
      });
    },
    gotoBpm(data, item, reportType) {
      this.cancel();
      var bpmUrl = this.bpmUrl;
      var rParam = {
        businessCategoryId: data.businessCategoryId,
        businessCategory: data.businessCategory,
        projectId: data.projectId,
        projectGlobalId:
          data.projectGlobalId == null ? "" : data.projectGlobalId,
        businessId: data.businessId,
        businessName: data.businessName,
        deptId: data.deptId,
        deptName: data.deptName,
        projectLeader: data.projectLeader,
        projectLeaderId: data.projectLeaderId,
        projectName: data.projectName,
        projectManager: data.projectManager,
        projectLeaderNo: data.projectLeaderNo,
        projectManagerNo: data.projectManagerNo,
        projectCode: data.projectCode,
        reportName: data.reportName,
        reportType: reportType,
        reportTypeCounts:this.reportTypeOptions.length
      };
      axios
        .post(bpmUrl + "/Portal/InstanceController/starInstance", rParam)
        .then(function(response) {
          if (response.status == 200 && response.data) {
            var code = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
            //code = Encrypt(code);
            window.open(
              bpmUrl +
                "/Portal/run.html?workflowCode=" +
                item +
                "&formId=" +
                response.data.formId +
                "&date=" +
                response.data.date +
                "&code=" +
                code
            );
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.guid || this.ids;
      this.$confirm(
        '是否确认删除造价报告号编号为"' + guids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delBmsCostNo(guids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.projectId = this.$route.params.id;
      const queryParams = this.queryParams;
      const dateRange = this.dateRange;
      const addDateRange = this.addDateRange(queryParams, dateRange)
      
      this.$confirm("是否确认导出所有符合条件的造价报告号数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportBmsCostNo(addDateRange);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    change(e) {
      this.$forceUpdate();
    },
    tableSortChange(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },//刷新数据
    refreshData() {
      this.business.businessData = undefined;
      this.business.reportTypeName = undefined;
      this.reportTypeOptions = [];
      this.getList();
      this.getBusinessOptions();
    },
    getBusinessOptions() {
      listNoCostNoList({ projectId: this.$route.params.id }).then(res => {
        if (res.code === 200) {
          this.businessOptions = res.data;
        }
      });
    },getShowReportTypeBidding(val) {
      this.businessOptions.forEach(item => {
        if (item.guid === val) {
          this.reportTypeOptions = item.reportTypes;
          this.business.reportTypeName = this.reportTypeOptions[0];
        }
      });
    },
    handleView (index, row) {
      this.visible = true
      this.business = row;
      this.getBusinessOptions();
      console.log(this.business);
    },
    /** 提交按钮 */
    submitMigrateForm: function () {
      this.getList();

      if (!this.business.businessData) {
        this.msgError("业务不能为空！");
        return false;
      }

      var checkParams = {
        businessTypeId: this.business.businessData.split(";")[1],
        projectId: this.$route.params.id,
        businessId: this.business.businessData.split(";")[0],
      };
      var updateHisGuid = this.business.guid;
      checkBmsCostNo(checkParams).then((res) => {
        if (res.code === 200 && res.data === 0) {
          this.business.businessId = this.business.businessData.split(";")[0];
          this.business.businessTypeId = this.business.businessData.split(";")[1];
          this.business.projectId = this.$route.params.id;
          this.business.costType = this.reportTypeOptions[0];
          this.business.guid= "";
          addBmsCostNo(this.business).then(response => {
          if (response.code === 200) {
            // this.msgSuccess("迁移成功");
            this.visible = false;
            this.updateBmsCostNoHis(updateHisGuid);
            this.refreshData();
          } else {
            this.msgError("迁移失败");
          }
        });
        } else {
          this.msgInfo(
            "本业务已生成造价报告号，请勿重复申请！点击刷新按钮重新载入数据！"
          );
        }
      });
    },
    updateBmsCostNoHis(updateHisGuid){
      var updateHisParam = {
        guid: updateHisGuid
      }
      if(updateHisGuid){
        updateBmsCostNoHistory(updateHisParam).then(response => {
            if (response.code === 200) {
              this.msgSuccess("迁移成功");
            }
        });
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.tabletitle {
  margin: 0 20px;
  .input-wrap {
    padding: 8px;
    display: flex;

    .input-label {
      min-width: 1em;
      max-width: 8em;
      color: rgba(0, 0, 0, 0.65);
      margin-right: 12px;
      display: flex;
      margin-top: 9px;
      flex: 0 0 90px;
      justify-content: flex-end;
    }

    .input-content {
      -webkit-box-flex: 1;
      flex-grow: 1;
      .el-select {
        width: 100%;
      }
    }
  }
}
.tablebox {
  height: 100%;
}
/deep/.el-table .cell {
  font-family: PingFangSC-Regular;
  color: rgba(0, 0, 0, 0.85);
  letter-spacing: 0;
  // text-align: center;
  a {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #1890ff;
    letter-spacing: 0;
    text-align: right;
    line-height: 14px;
    margin: 0 5px;
  }
}
/deep/.el-form-item--medium .el-form-item__content {
  line-height: 32px;
}

/deep/.el-form {
  .el-cascader--medium {
    .el-input--medium .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
  }
}
</style>